package im.engure.common.server.http.handler;

import im.engure.common.protocol.Invocation;
import im.engure.common.registery.LocalServiceRegistry;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;

public class HttpServletHandler {

    public void handler(HttpServletRequest req, HttpServletResponse resp) {

        try {
            Invocation invocation = (Invocation) new ObjectInputStream(req.getInputStream()).readObject();

            String interfaceName = invocation.getInterfaceName();
            String methodName = invocation.getMethodName();
            Class<?>[] paramTypes = invocation.getParamTypes();
            Object[] params = invocation.getParams();

            Class<?> serviceImplClazz = LocalServiceRegistry.getServiceImpl(interfaceName);
            Object serviceImplInstance = serviceImplClazz.newInstance();
            Method targetMethod = serviceImplClazz.getMethod(methodName, paramTypes);
            Object res = targetMethod.invoke(serviceImplInstance, params);

            //将返回结果写入响应
            //todo 统一方法结果格式
            //todo 将结果序列化成 JSON 格式
            IOUtils.write(res.toString(), resp.getOutputStream(), StandardCharsets.UTF_8);

        } catch (IOException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException |
                 InstantiationException | IllegalAccessException e) {
            e.printStackTrace();

            try {
                String message = "调用失败【" + e.getMessage() + "】";
                IOUtils.write(message, resp.getOutputStream(), StandardCharsets.UTF_8);
            } catch (IOException ex) {
                System.err.println("写入响应失败");
                e.printStackTrace();
            }

        }

    }
}
